package com.wuchengdong.web.interceptor;
import com.wuchengdong.web.extend.auth.AuthTemplate;
import com.wuchengdong.web.extend.utils.UserHolder;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import static com.wuchengdong.web.extend.utils.CookieUtil.getByName;


/**
 * 身份认证/鉴权
 */
@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Autowired
    AuthTemplate authTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //读取前端的Token
        Cookie cookie = getByName(request.getCookies(), "auth");
        if (cookie == null) return false;
        String token = cookie.getValue();
        //验证Token
        int userId = authTemplate.getUserByToken(token);
        if(userId == -1) {
            //token错误 直接拒绝即可 前端被拒绝后 删除原有的token 重新登录
            System.out.println("拦截："+request.getRequestURI());
            return false;
        }
        UserHolder.saveUserId(userId);
        System.out.println("放行："+request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
